// pages/product/productDetail/index.js
const app = getApp()
const service = require('../../../service/port.js')
const evaluateService = require("../../../service/evaluate")
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    isServiceTipHidden: true, //控制服务隐藏的标记值
    swiperList: [],
    productDetailImg: [],
    show: false,
    detail: {
      price: 10,
      monthSale: 1000,
      diamond: 3,
      name: "碧耐丝草本植萃护发泡泡染"
    },
    spudetail: {},
    servicetext: '',
    specification: [{
      title: "规格分类",
      tag: []
    }],
    currentsku: '',
    currentInfo: {},
    currentnum: 1,
    isnewOpen: true,
    spuId: '',
    serviceList: [],
    showLogin: false,
    showbtn: true,
    disabled: false,
    commentNum: 0,
    commentList: [],
    images: [
      "https://img.yzcdn.cn/vant/cat.jpeg",
      "https://img.yzcdn.cn/vant/cat.jpeg",
      "https://img.yzcdn.cn/vant/cat.jpeg"
    ],
    nomoredata: false,
    videoUrl: [],
    isLogin: false,//判断是否已经登录 用于分享按钮

  },
  showServiceTip() {
    this.setData({
      isServiceTipHidden: false
    })
  },
  hideServiceTip() {
    this.setData({
      isServiceTipHidden: true
    })
  },
  changeSwiper(e) {
    //console.log(e)
    if (e.detail.current == 0) {
      this.videoContext.play()
    } else {
      this.videoContext.stop()
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(1111, options)
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        isLogin: true,
      })
    } else {
      this.setData({
        isLogin: false
      })
    }
    if (options.type == "pack") {
      this.setData({
        showbtn: false
      })
    }
    if (options.share == "true") {
      service.sharegoods(options.customerId, res => {
        console.log(res)
      })
    }
    const id = options.id || options.scene;
    this.setData({
      spuId: id
    })
    wx.showLoading({
      title: '加载中...',
    })
    service.getItemDetail(id, wx.getStorageSync('userInfo').id ? wx.getStorageSync('userInfo').id : null, res => {
      //console.log(res);
      if (res.code != '00000') {
        wx.showToast({
          title: '商品已下架！',
          icon: 'none',
          duration: 3000,
          mask: true,
          success() {
            wx.navigateBack({
              delta: 1
            })
          }
        })
        return
      }
      var imgJson = JSON.parse(res.data.spudetail.images);
      //console.log(imgJson);
      var list = imgJson.temBanner.split(",");
      var imgList = imgJson.itemDetail.split(",");
      res.data.tbSpu.image = list[0];
      this.setData({
        spudetail: res.data.spudetail,
        detail: res.data.tbSpu,
        swiperList: list,
        productDetailImg: imgList,
        currentInfo: res.data.tbSpu,
        videoUrl: res.data.spudetail.video
      })
      service.getserviceList(res1 => {
        var serviceidlist = res.data.tbSpu.serviceIds.split(',');
        //console.log(res1);
        var text = '';
        var list = [];
        res1.data.forEach(item => {
          serviceidlist.forEach(item1 => {
            if (item1 == item.id) {
              text += item.serviceName + '  ';
              list.push(item);
            }
          })
        })
        this.setData({
          servicetext: text,
          serviceList: list
        })
      })
    })
    evaluateService.getAllevaluate({
      "data": {
        //用户id
        "spuId": id
      },
      //分页
      "queryRequest": {
        //页码
        "pageNum": 1,
        //面数据量
        "pageSize": 3
      }

    }, res => {
      console.log(res)

      this.setData({
        commentNum: res.data.total
      })
      if (res.data.rows.length == 0) {
        this.setData({
          nomoredata: true
        })
      } else {
        for (let i = 0; i < res.data.rows.length; i++) {
          const element = res.data.rows[i];
          element.overall = ((element.score * 0.7 * 100 + element.pdScore * 0.3 * 100) / 100).toFixed(1)
        }
        this.setData({
          commentList: res.data.rows
        })
      }

    })

  },
  loginTo() {
    this.setData({
      showLogin: true
    })
  },
  previewImg: function (e) {
    //console.log(e);
    //var item = e.currentTarget.dataset.item;
    var imgUrls = e.currentTarget.dataset.item;
    //图片预览
    wx.previewImage({
      current: imgUrls, // 当前显示图片的http链接
      urls: this.data.swiperList
    })
  },
  previewImg1(e) {
    //console.log(e);
    var list = [];
    e.currentTarget.dataset.imglist.forEach(element => {
      list.push(element.picUrl)
    });
    var imgUrls = e.currentTarget.dataset.item;
    //图片预览
    wx.previewImage({
      current: imgUrls, // 当前显示图片的http链接
      urls: list
    })
  },
  onClose: function () {
    this.setData({
      show: false
    })
  },
  onClose1: function () {
    this.setData({
      showLogin: false
    })
  },
  goAll() {
    wx.navigateTo({
      url: '/pages/product/allEvaluate/index?spuId=' + this.data.spuId,
    })
  },
  showpop: function () {
    if (app.globalData.userInfo == null) {
      // this.setData({
      //   isnewOpen: false
      // })
      // wx.navigateTo({
      //   url: '/pages/remindlogin/index',
      // })
      this.setData({
        showLogin: true
      })
    } else {

      service.getSku(this.data.spuId, (res) => {

        this.setData({
          currentsku: res.data[0].id,
          currentInfo: res.data[0],
          specification: [{
            title: "规格分类",
            tag: res.data
          }],
        })
        this.setData({
          show: true
        })
      })

    }

  },

  handlePoster() {
    let param = {
      goodsName: this.data.currentInfo.title,
      goodsPrice: this.data.currentInfo.price / 100,
      goodsImage: this.data.currentInfo.image,
      id: this.data.currentInfo.id
    }
    let jsonP = JSON.stringify(param)
    wx.navigateTo({
      url: `/pages/goodsPoster/index?param=${jsonP}`,
    })
  },

  choose: function (e) {
    console.log(e)
    // var index = e.currentTarget.dataset.index;
    // var array = e.currentTarget.dataset.array;

    // array.forEach(item=>{
    //   item.active=false
    // })
    // array[index].active=true;
    if (e.currentTarget.dataset.stock == 0) {
      this.setData({
        disabled: true
      })
    } else {
      this.setData({
        disabled: false
      })
    }
    this.setData({
      currentsku: e.currentTarget.dataset.item.id,
      currentInfo: e.currentTarget.dataset.item
    })

  },
  handleContact(e) {
    console.log(e.detail.path)
    console.log(e.detail.query)
  },
  //添加购物车
  addcart() {
    if (this.data.currentsku == '') {
      Toast.fail('请选择规格');
      return
    }
    if (this.data.currentInfo.stock == 0) {
      Toast.fail('该商品规格无库存！');
      return
    }
    service.addcart({
      customerId: wx.getStorageSync('userInfo').id,
      spuId: this.data.spuId,
      skuId: this.data.currentsku,
      num: this.data.currentnum
    }, res => {
      Toast.success('已加入购物车');
      this.setData({
        show: false
      })
    })
  },
  onChange(event) {
    console.log(event.detail);
    this.setData({
      currentnum: event.detail
    })
  },
  loginsucc() {
    this.setData({
      showLogin: false,
      isLogin: true
    })
    if (wx.getStorageSync('userInfo').mobile == null || wx.getStorageSync('userInfo').mobile == "") {
      wx.navigateTo({
        url: 'pages/phone/index',
      })
    }
  },
  buyNow() {
    if (this.data.currentsku == '') {
      Toast.fail('请选择规格');
      return
    }
    if (this.data.currentInfo.stock == 0) {
      Toast.fail('该商品规格无库存！');
      return
    }
    // wx.setStorageSync("productInfo", this.data);
    // this.setData({
    //   show: false
    // })
    // wx.navigateTo({
    //   url: '/pages/order/confirmorder/index',
    // })

    this.toFinalConfirmOrder()

  },
  toFinalConfirmOrder() {
    let totalMoney = this.data.currentnum * this.data.currentInfo.price
    let currentInfo = {
      ...this.data.currentInfo,
      num: this.data.currentnum //购买数量
    }
    let orderInfo = {
      type: '4',
      shoppingList: [currentInfo],
      totalMoney: totalMoney,
    }

    console.log('orderInfo===========')
    console.log('正常商品', orderInfo)
    console.log('orderInfo===========')
    orderInfo = JSON.stringify(orderInfo)
    wx.navigateTo({
      url: `/pages/order/finalComfirmOrder/index?orderInfo=${orderInfo}`,
    })
  },










  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.videoContext = wx.createVideoContext('myVideo')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (!this.data.isnewOpen) {
      this.setData({
        show: true
      })
    }
    if (wx.getStorageSync('userInfo')) {
      this.setData({
        isLogin: true,
      })

    } else {
      this.setData({
        isLogin: false
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    console.log(e)
    //this.service
    // if(e.from=="button"){

    // }
    if (app.globalData.userInfo == null) {
      // this.setData({
      //   isnewOpen: false
      // })
      // wx.navigateTo({
      //   url: '/pages/remindlogin/index',
      // })
      this.setData({
        showLogin: true
      })
    } else {
      return {
        title: this.data.detail.title,
        path: "/pages/product/productDetail/index?id=" + this.data.spuId + "&share=true&customerId=" + wx.getStorageSync('userInfo').id,
        success: function (res) {
          // 转发成功，可以把当前页面的链接发送给后端，用于记录当前页面被转发了多少次或其他业务
          console.log(res)
        },
        fail: function (res) {
          // 转发失败
        }
      }
    }
  }
})